package eatwatch;

import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

class FormDailyIntake extends Form implements CommandListener, ItemStateListener, ItemCommandListener
{
	static 	private final	String	mOriginalTitle  = "Consum zilnic";

	private final	Command 		cmdBack  		= new Command ("Inapoi", Command.BACK, 0);
	private final	Command 		cmdAdd  		= new Command ("Adauga", Command.OK, 0);
	private final	Command 		cmdSelect  		= new Command ("Selecteaza", Command.ITEM, 0);
	private	final	IDatabase		mDatabase   	= EatWatch.mDatabase;
	private 		MIDlet 			mMIDlet 		= null;
	private 		Displayable		mPrevScreen		= null;
	private			TextField		mIngredient 	= new TextField ("Ingredient", "", 50, TextField.ANY);
	private			LookupField     mIngrList   	= new LookupField ("");
	private 		TextField 		txtCalories		= new TextField ("Calorii", "", 4, TextField.NUMERIC);
	private 		ChoiceGroup		chgMeasure		= new ChoiceGroup ("", ChoiceGroup.POPUP, new String[] {"100g", "buc"}, null);
	private 		TextField 		txtQuantity		= new TextField ("Cantitate", "", 4, TextField.NUMERIC);
	private   		boolean			mUpdateMode		= false;
	private 		Date			mRecordDate		= null;

	public FormDailyIntake (MIDlet midlet)
	{
		super (mOriginalTitle);
		mMIDlet = midlet;

		append (mIngredient);
		append (mIngrList);
		append (txtCalories);
		append (chgMeasure);
		append (txtQuantity);

		mIngredient.setDefaultCommand (cmdSelect);
		mIngredient.setItemCommandListener (this);

		mIngrList.setDefaultCommand (cmdSelect);
		mIngrList.setItemCommandListener (this);

		addCommand (cmdBack);
		addCommand (cmdAdd);
		setCommandListener (this);
		setItemStateListener (this);
	}

	public void commandAction(Command c, Displayable d)
	{
		if (c == cmdBack && d == this)
			Display.getDisplay (mMIDlet).setCurrent (mPrevScreen);
		else if (c == cmdAdd && d == this) {
			if (AddRecord ()) {
				if (mPrevScreen.getClass().getName().equals ("eatwatch.FormDailyReport"))
					((FormDailyReport)mPrevScreen).Show ();
				else
					Display.getDisplay (mMIDlet).setCurrent (mPrevScreen);
			}
		}
	}

	public void itemStateChanged(Item item) {
		if (item == mIngredient)
			mIngrList.Search (mIngredient.getString ());
		else if (item == txtQuantity || item == txtCalories)
			ComputeCalories ();
	}

	public void commandAction(Command c, Item item)
	{
		String ingredient = null;
		if (item == mIngredient)
			ingredient = mIngredient.getString ();
		else {
			ingredient = mIngrList.GetString (mIngrList.GetSelectedIndex ());
			mIngredient.setString (ingredient);
		}
		mDatabase.Open ("calories", "ingredient");
		Record rec = mDatabase.FindRecord ("ingredient", ingredient);
		mDatabase.Close ();
		if (rec != null) {
			txtCalories.setString (rec.GetField("calories").toString ());
			chgMeasure.setSelectedIndex (((Integer)rec.GetField("MU")).intValue (), true);
			Display.getDisplay (mMIDlet).setCurrentItem (txtQuantity);
		}
		else {
			txtCalories.setString ("");
			chgMeasure.setSelectedIndex (0, true);
			Display.getDisplay (mMIDlet).setCurrentItem (txtCalories);
		}
	}

	public void ShowAdd (Displayable prevForm)
	{
		mUpdateMode = false;
		mPrevScreen = prevForm;
		PrepareForm ();
		ClearForm ();
		Display.getDisplay (mMIDlet).setCurrent (this);
	}

	public void ShowUpdate (Displayable prevForm, Date recordDate)
	{
		mUpdateMode = true;
		mRecordDate = recordDate;
		mPrevScreen = prevForm;
		PrepareForm ();
		DisplayRecord (recordDate);
		Display.getDisplay (mMIDlet).setCurrent (this);
	}

	private void PrepareForm ()
	{
		mIngrList.DeleteAll ();
		mDatabase.Open ("calories", "ingredient");
		Record rec = null;
		while ((rec = mDatabase.ReadRecord ()) !=null) {
			String ingredient = rec.GetField ("ingredient").toString ();
			mIngrList.Append (ingredient);
		}
		mDatabase.Close ();
	}

	private void ComputeCalories ()
	{
		float total = 0.0f;
		if (txtCalories.getString ().length () != 0 &&
		    txtQuantity.getString ().length () != 0) {
			float calories = Integer.parseInt (txtCalories.getString ());
			float divideBy = chgMeasure.getSelectedIndex () == 0 ? 100 : 1;
			float quantity = Integer.parseInt (txtQuantity.getString ());
			total = calories * quantity / divideBy;
		}

		setTitle (mOriginalTitle + (total != 0.0f ? " [" + total + "]" : ""));
	}

	private boolean AddRecord ()
	{
		if (!ValidateForm ())
			return false;

		Record rec = null;
		if (!mUpdateMode) {
			// first check the calories table
			mDatabase.Open ("calories", "ingredient");
			rec = mDatabase.FindRecord ("ingredient", mIngredient.getString ());
			mDatabase.Close ();
			if (rec == null) {
				rec = new Record ();
				rec.SetField ("ingredient", mIngredient.getString ());
				rec.SetField ("calories", new Integer (Integer.parseInt (txtCalories.getString ())));
				rec.SetField ("MU", new Integer (chgMeasure.getSelectedIndex ()));
				mDatabase.Open ("calories");
				mDatabase.AddRecord (rec);
				mDatabase.Close ();
			}
			mDatabase.Open ("intake");
			rec = new Record ();
		}
		else {
			mDatabase.Open ("intake");
			rec = mDatabase.FindRecord ("date", mRecordDate);
		}

		// add this item to daily intake
		rec.SetField ("date", Calendar.getInstance ().getTime ());
		rec.SetField ("ingredient", mIngredient.getString ());
		rec.SetField ("calories", new Integer (Integer.parseInt (txtCalories.getString ())));
		rec.SetField ("MU", new Integer (chgMeasure.getSelectedIndex ()));
		rec.SetField ("quantity", new Integer (Integer.parseInt (txtQuantity.getString ())));

		if (mUpdateMode)
			mDatabase.UpdateRecord (rec);
		else
			mDatabase.AddRecord (rec);

		mDatabase.Close ();
		return true;
	}

	private void DisplayRecord (Date recordDate)
	{
		if (recordDate == null) {
			ClearForm ();
			return;
		}
		mDatabase.Open ("intake");
		Record rec = mDatabase.FindRecord ("date", mRecordDate);
		mDatabase.Close ();

		if (rec == null) {
			ClearForm ();
			return;
		}

		mIngredient.setString ((String)rec.GetField ("ingredient"));
		txtCalories.setString (rec.GetField ("calories").toString ());
		chgMeasure.setSelectedIndex (((Integer)rec.GetField ("MU")).intValue (), true);
		txtQuantity.setString (rec.GetField ("quantity").toString ());

		ComputeCalories ();
	}

	private void ClearForm ()
	{
		mIngredient.setString ("");
		txtCalories.setString ("");
		chgMeasure.setSelectedIndex (0, true);
		txtQuantity.setString ("");
	}

	private boolean ValidateForm ()
	{
		Item item = null;
		if (mIngredient.getString ().length () == 0)
			item = mIngredient;
		else if (txtCalories.getString ().length () == 0)
			item = txtCalories;
		else if (txtQuantity.getString ().length () == 0)
			item = txtQuantity;

		if (item != null) {
			Display.getDisplay (mMIDlet).setCurrentItem (item);
			return false;
		}
		return true;
	}
}